<template>
  <div class="edu-page-warp">
    <el-card shadow="never">
      <div class="edu-opertion-bar">
        <el-row :gutter="20" style="line-height: 32px;">
          <el-col :span="4">
            <div class="minorGrade">是否允许多重登录：</div>
          </el-col>
          <el-col :span="3">
            <el-switch
              v-model="loginConfig.configSwitch"
              active-value="1"
              inactive-value="0"
              active-text="允许"
              active-color="#13CE66"
              inactive-text="禁止"
              @change="mulLoginConfig"
            ></el-switch>
          </el-col>
        </el-row>
      </div>

      <div class="edu-opertion-bar">
        <el-row :gutter="20" style="line-height: 32px;">
          <el-col :span="4">
            <div class="minorGrade">当前在线人数：</div>
          </el-col>
          <el-col :span="3">
            <el-input disabled v-model="onlineNo.onlineNumber"></el-input>
          </el-col>
        </el-row>
      </div>

      <div class="edu-opertion-bar">
        <el-row :gutter="24" style="line-height: 32px;">
          <el-col :span="18">
            <div class="float-left">系统最大连接数分时段配置</div>
          </el-col>
          <el-col :span="6">
          <div class="float-right">
            <el-button @click="showAddBox" type="primary" >{{$t('message.add')}}</el-button>
          </div>
        </el-col>
        </el-row>
      </div>

      <el-table :data="sysParam" style="width:100%" stripe>
					<el-table-column type="selection" width="42"></el-table-column>
					<el-table-column type="index" label="编号" min-width="100"></el-table-column>
          <el-table-column label="时段" min-width="120">
            <template slot-scope="scope">
              <span :title="scope.row.allowTimeStart">{{formatDate(scope.row.allowTimeStart)}}</span>
              <span>-</span>
              <span :title="scope.row.allowTimeEnd">{{formatDate(scope.row.allowTimeEnd)}}</span>
            </template>
          </el-table-column>
					<el-table-column label="系统最大连接数" min-width="100">
            <template slot-scope="scope">
              <span :title="scope.row.maxOnlineNumber">{{scope.row.maxOnlineNumber}}</span>
            </template>
          </el-table-column>

					<el-table-column label="操作" min-width="100">
						<template slot-scope="scope">
							<el-button type="text" @click="showEditBox(scope.row)" >{{$t('message.edit')}}</el-button>
							<el-button type="text" @click="_delete(scope.row.id)" >{{$t('message.delete')}}</el-button>
						</template>
					</el-table-column>
				</el-table>
        <el-row>
          <el-col>
            <el-pagination
              @size-change="handleSizeChange1"
              @current-change="handlePageNumChange1"
              :current-page="addSysParam.pageNum_"
              :page-sizes="[20,50,100,500,1000]"
              :page-size="addSysParam.pageSize_"
              layout="total, sizes, prev, pager, next, jumper"
              :total="addSysParam.total" style="float: right;margin:10px 60px 0 0;">
            </el-pagination>
          </el-col>
        </el-row>
    </el-card>

    <el-dialog title="新增" width="40%" :visible.sync="showAddDialog" @close="cancelCreate">
			<el-form :model="addSysParam" label-width="90px" label-position="right" class="pd-20px"
        :rules="rules" ref="addSysParam">
        <el-row :gutter="24">
					<el-col :span="12">
            <el-form-item label="最大连接数" prop="maxOnlineNumber">
							<el-input v-model="addSysParam.maxOnlineNumber" placeholder="" maxlength="7"></el-input>
						</el-form-item>
					</el-col>
        </el-row>
        <el-row :gutter="24">
					<el-col :span="24">
						<el-form-item label="时段" prop="allowTime">
              <!-- <el-date-picker
                v-model="addSysParam.allowTime"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="timestamp"

                format="yyyy-MM-dd"
                style="width:100%"
                :picker-options="pickerOptions">
              </el-date-picker> -->
              <el-date-picker
                v-model="addSysParam.allowTime"
                type="datetimerange"
                :picker-options="pickerOptions"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="timestamp"
                format="yyyy-MM-dd HH:mm:ss"
                style="width:100%"
                align="right">
              </el-date-picker>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<span slot="footer">
				<el-button @click="showAddDialog = false">{{$t('message.cancel')}}</el-button>
				<el-button type="primary" @click="_create">{{$t('message.confirm')}}</el-button>
			</span>
		</el-dialog>

		<el-dialog title="修改" width="40%" :visible.sync="showEditDialog">
			<el-form :model="editSysParam" label-width="90px" label-position="right" class="pd-20px"
        :rules="rules" ref="editSysParam">
				<el-row :gutter="24">
					<el-col :span="16">
            <el-form-item label="最大连接数" prop="maxOnlineNumber">
							<el-input v-model="editSysParam.maxOnlineNumber" placeholder=""></el-input>
						</el-form-item>
					</el-col>
        </el-row>
        <el-row :gutter="24">
					<el-col :span="24">
						<el-form-item label="时段" prop="allowTime">
							<el-date-picker
                v-model="editSysParam.allowTime"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="timestamp"

                format="yyyy-MM-dd"
                style="width:100%"
                :picker-options="pickerOptions">
              </el-date-picker>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<span slot="footer">
				<el-button @click="showEditDialog = false">{{$t('message.cancel')}}</el-button>
				<el-button type="primary" @click="_edit">{{$t('message.confirm')}}</el-button>
			</span>
		</el-dialog>
</div>
</template>
<script>
import {
  findSysParam,
  addSystemParam,
  updateSysParam,
  deleteSysParam,
  updateLoginConfig,
  onlineNumberListener,
  getMulLoginMark
} from "common/src/api/systemParam";

export default {
  name: "SystemParam",
  data() {
    var validateId = (rule, value, callback) => {
      var numberReg = /^[0-9]*[1-9][0-9]*$/;
      var regSpace = /\s/;
      if (regSpace.test(value)) {
        callback(new Error(this.$t('message.canNotSpace')));
      } else if (!numberReg.test(value)) {
        callback(new Error(this.$t('message.mustNumber')));
      } else {
        callback();
      }
    };
    var validateTime = (rule, value, callback) => {
      var flag = true;
      for (var i=0;i<this.sysParam.length;i++) {
        if (this.editSysParam.id != null && this.editSysParam.id == this.sysParam[i].id) {
          continue;
        }
        if ((value[0] > this.sysParam[i].allowTimeStart && value[0] < this.sysParam[i].allowTimeEnd)
          || (value[1] > this.sysParam[i].allowTimeStart && value[1] < this.sysParam[i].allowTimeEnd)
          || (value[0] > this.sysParam[i].allowTimeStart && value[1] < this.sysParam[i].allowTimeEnd)
          || (value[0] < this.sysParam[i].allowTimeStart && value[1] > this.sysParam[i].allowTimeEnd)
          || (value[0] == this.sysParam[i].allowTimeStart || value[1] == this.sysParam[i].allowTimeEnd)
        ) {
          flag = false;
          callback(new Error(this.$t('message.repeatTime')));
          break;
        }
      }
      if (flag) {
        callback();
      }
    };
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      onlineNo: {
        onlineNumber: ""
      },
      loginConfig: {
        configSwitch: true
      },
      sysParam: [],
      showAddDialog: false,
      showEditDialog: false,
      addSysParam: {
        id:"",
        allowTimeStart: "",
        allowTimeEnd: "",
        maxOnlineNumber: "",
        allowTime: [],
        condition: "",
        pageNum_: 1,
        total: 0,
        pageSize_: 20
      },
      editSysParam: {
        id:"",
        allowTimeStart: "",
        allowTimeEnd: "",
        maxOnlineNumber: "",
        allowTime: [],
        condition: "",
        pageNum_: 1,
        total: 0,
        pageSize_: 20
      },
      rules: {
        maxOnlineNumber: [
          {
            required: true,
            message: "请输入最大连接数",
            trigger: "blur"
          },
          {
            validator: validateId,
            trigger: "blur"
          }
        ],
        allowTime: [
          {
            required: true,
            message: "请选择时间",
            trigger: "blur"
          },
          {
            validator: validateTime,
            trigger: "blur"
          }
        ]
      },
    };
  },
  created() {
    this.getSystemParamList();
    this.getOnlineNumber();
    this.getLoginMark();
    //this.initWebSocket();
  },
  mounted() {
    //this.timer = setInterval(this.getOnlineNumber, 10000);

  },
  destroyed :function() {
    //this.webSocketclose();
  },
  computed: {
    
  },
  methods: {
    // initWebSocket(){//建立连接
    //     //初始化weosocket
    //     const wsuri = "ws://127.0.0.1:8089/websocket";
    //     //建立连接
    //     this.websock = new WebSocket(wsuri);
    //     //连接成功
    //     this.websock.onopen = this.websocketonopen;
    //     //连接错误
    //     this.websock.onerror = this.websocketonerror;
    //     //接收信息
    //     this.websock.onmessage = this.websocketonmessage;
    //     //连接关闭
    //     this.websock.onclose = this.websocketclose;
    // },
    // reconnect() {//重新连接
    //     var that = this;
    //     if(that.lockReconnect) {
    //         return;
    //     };
    //     that.lockReconnect = true;
    //     //没连接上会一直重连，设置延迟避免请求过多
    //     that.timeoutnum && clearTimeout(that.timeoutnum);
    //     that.timeoutnum = setTimeout(function () {
    //         //新连接
    //         that.initWebSocket();
    //         that.lockReconnect = false;
    //     },5000);
    // },
    // reset(){//重置心跳
    //     var that = this;
    //     //清除时间
    //     clearTimeout(that.timeoutObj);
    //     clearTimeout(that.serverTimeoutObj);
    //     //重启心跳
    //     that.start();
    // },
    // start(){//开启心跳
    //     var self = this;
    //     self.timeoutObj && clearTimeout(self.timeoutObj);
    //     self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
    //     self.timeoutObj = setTimeout(function(){
    //         //这里发送一个心跳，后端收到后，返回一个心跳消息，
    //         if (self.websock.readyState == 1) {//如果连接正常
    //             self.websock.send("heartCheck");
    //         }else{//否则重连
    //             self.reconnect();
    //         }
    //         self.serverTimeoutObj = setTimeout(function() {
    //             //超时关闭
    //             self.websock.close();
    //         }, self.timeout);

    //     }, self.timeout)
    // },
    // websocketonopen() {//连接成功事件
    //     //生成二维码(参数内容，canvas的id)
    //     //s.qrcode(this.charId,"canvas")
    //     //提示成功
    //     //s.success("连接成功",3)
    //     //开启心跳
    //     this.start();
    // },
    
    // websocketonerror(e) {//连接失败事件
    //     //错误
    //     console.log("WebSocket连接发生错误");
    //     //错误提示
    //     //s.error("Websocket error, Check you internet!")
    //     //重连
    //     //this.reconnect();
    // },
    // websocketclose(e) {//连接关闭事件
    //     //关闭
    //     console.log("connection closed (" + e.code + ")");
    //     //提示关闭
    //     //s.error("连接已关闭",3);
    //     //重连
    //     //this.reconnect();
    // },
    // websocketonmessage(event) {//接收服务器推送的信息
    //     //打印收到服务器的内容
    //     console.log(event.data);
    //     //收到服务器信息，心跳重置
    //     this.reset();
    // },
    // websocketsend(msg) {//向服务器发送信息
    //     //数据发送
    //     this.websock.send(msg);
    // },
    formatDate(timenumber) {
      return moment(timenumber).format('YYYY/MM/DD HH:mm:ss');
    },
    handleSizeChange1(val) {
      this.sysParam.pageSize_ = val;
      this.onSubmit();
    },
    handlePageNumChange1(val) {
      this.sysParam.pageNum_ = val;
      this.onSubmit();
    },
    onSubmit(callback) {
      this.getSystemParamList(callback);
    },
    getLoginMark() {
      getMulLoginMark().then(response => {
        if (response.code == 200) {
          this.loginConfig.configSwitch = response.data;
        } else throw response.code;
      })
    },
    getOnlineNumber() {
      onlineNumberListener(this.onlineNo).then(response => {
        if (response.code == 200) {
          this.onlineNo.onlineNumber = response.data;
        } else throw response.code;
      });
    },
    mulLoginConfig(status) {
      this.loginConfig.configSwitch = status;
      updateLoginConfig(this.loginConfig).then(response => {
        if (response.code == 200) {
          this.$message({
            type: "success",
            message: "修改成功"
          });
        } else throw response.msg;
      });
    },
    getSystemParamList() {
      findSysParam(this.addSysParam).then(response => {
        if (response.code == 200) {
          this.sysParam = response.data.list;
          this.addSysParam.total = response.data.total_;
        } else throw response.code;
      });
    },
    showEditBox(data) {
      this.editSysParam = data;
      this.showEditDialog = true;
    },
    _delete(_id) {
      let _that = this;
      this.$confirm("确定要删除该记录吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(_ => {
          doDelete(_that);
        })
        .catch(error => {
          console.log(error);
        });
      function doDelete(that) {
        deleteSysParam({ id: _id })
          .then(res => {
            if (res.code) {
              that.onSubmit();
              that.$message({
                type: "success",
                message: "删除成功"
              });
            } else throw res.code;
          })
          .catch(error => {
            that.$message({
              type: "error",
              message: "操作失败"
            });
          });
      }
    },
    showAddBox() {
      this.showAddDialog = true;
    },
    cancelCreate() {},
    _create() {
      this.addSysParam.allowTimeStart = this.addSysParam.allowTime[0];
      this.addSysParam.allowTimeEnd = this.addSysParam.allowTime[1];
      this.$refs.addSysParam.validate(valid => {
        if (valid) {
          addSystemParam(this.addSysParam)
            .then(response => {
              if (response.code == 200) {
                this.$message({
                  type: "success",
                  message: "添加成功"
                });
                this.getSystemParamList();
                this.showAddDialog = false;
                this.$refs.addSysParam.resetFields();
              } else if (response.code == 300)
                this.$message({
                  type: "error",
                  message: "账号已存在, 请重试!"
                });
            })
            .catch(error => {
              this.$message({
                type: "error",
                message: "添加出错, 请重试!"
              });
            });
        }
      });
    },
    _edit() {
      this.editSysParam.allowTimeStart = this.editSysParam.allowTime[0];
      this.editSysParam.allowTimeEnd = this.editSysParam.allowTime[1];
      this.$refs.editSysParam.validate(valid => {
        if (valid) {
          updateSysParam(this.editSysParam)
            .then(response => {
              if (response.code == 200) {
                this.$message({
                  type: "success",
                  message: "修改成功"
                });
                this.getSystemParamList();
                this.showEditDialog = false;
                this.$refs.editSysParam.resetFields();
              } else throw response.code;
            })
            .catch(error => {
              this.$message({
                type: "error",
                message: "编辑出错, 请重试!"
              });
            });
        }
      });
    },
    queryAllSysParam() {
      findSysParam(this.localUserForm).then(response => {
        if (response.code == 200) {
          this.sysParam = response.data.list;
          this.addSysParam.total = response.data.total_;
        } else throw response.code;
      });
    },
  }
};
</script>
<style>
.minorGrade {
    font-family: "微软雅黑";
    font-size: 14px;
}
</style>
